package cn.javaxc.process.service;

import java.io.*;
import java.util.*;
import java.util.zip.ZipInputStream;
import javax.servlet.http.HttpServletRequest;


import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricActivityInstanceQuery;
import org.activiti.engine.task.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import cn.javaxc.mvcwork.modules.file.FileInfo;

import cn.javaxc.model.base.*;

@Service
public class ProcessDefinitionService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RepositoryService repositoryService;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int deleteProcessDeploymentByIds(String deploymentIds) {
        int counter = 0;
        for (String deploymentId: deploymentIds.split(",")) {
            List<ProcessInstance> instanceList = runtimeService.createProcessInstanceQuery()
                    .deploymentId(deploymentId)
                    .list();
            if (!CollectionUtils.isEmpty(instanceList)) continue;   // 跳过存在流程实例的流程定义
            repositoryService.deleteDeployment(deploymentId, true); // true 表示级联删除引用，比如 act_ru_execution 数据
            counter++;
        }
        return counter;
    }

//    @Transactional
    public void deployProcessDefinition(HttpServletRequest request) throws FileNotFoundException {
		File file=null;
		if (request instanceof DefaultMultipartHttpServletRequest){
			if (((DefaultMultipartHttpServletRequest)request).getFile("MVC_FILE") instanceof FileInfo){
				file=((FileInfo)((DefaultMultipartHttpServletRequest)request).getFile("MVC_FILE")).getLocalFile();
			}
		}
        if (file!=null&&file.exists()) {
			String filePath=file.getPath();
            if (filePath.endsWith(".zip")) {
                ZipInputStream inputStream = new ZipInputStream(new FileInputStream(file));
                repositoryService.createDeployment()
                        .addZipInputStream(inputStream)
                        .deploy();
            } else if (filePath.endsWith(".bpmn")) {
				Deployment deployment=repositoryService.createDeployment()
                        .addInputStream(filePath, new FileInputStream(file))
                        .deploy();
            }
        }
		file.delete();
    }


    @Autowired
    private HistoryService historyService;

    public SQLList selectHistoryList(String processInstanceId, String getAssignee,String getActivityName) {
        SQLList activityList = new SQLList();
        HistoricActivityInstanceQuery query = historyService.createHistoricActivityInstanceQuery();
        if (SQL.isNotNull(getAssignee)) {
            query.taskAssignee(getAssignee);
        }
        if (SQL.isNotNull(getActivityName)) {
            query.activityName(getActivityName);
        }
        List<HistoricActivityInstance> list = query.processInstanceId(processInstanceId)
                .activityType("userTask")
                .finished()
                .orderByHistoricActivityInstanceStartTime()
                .desc()
                .list();
//        list.forEach(instance -> {
		for (HistoricActivityInstance instance:list){
            SQLMap activity = new SQLMap();
			activity.put("activity",instance);
            String taskId = instance.getTaskId();
            List<Comment> comment = taskService.getTaskComments(taskId, "comment");
            if (!CollectionUtils.isEmpty(comment)) {
				String msg=comment.get(0).getFullMessage();
				try{
					activity.put("comment",new String(msg.getBytes(),"UTF-8"));					
				}catch(UnsupportedEncodingException e){
				}
            }
            activityList.add(activity);
        };
        return activityList;
    }
};
